package com.hrma.services.impl;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.hrma.dao.EmployeeMapper;
import com.hrma.dao.PermissionMapper;
import com.hrma.entity.*;
import com.hrma.entity.exception.UserNameOrPasswordException;
import com.hrma.services.EmployeeService;
import com.hrma.utils.UserUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Primary
@Slf4j
public class EmployeeImpl implements EmployeeService {
    private final EmployeeMapper employeeMapper;
    private final PermissionMapper permissionMapper;

    public EmployeeImpl(EmployeeMapper employeeMapper, PermissionMapper permissionMapper) {
        this.employeeMapper = employeeMapper;
        this.permissionMapper = permissionMapper;
    }

    @Override
    public Employee add(Employee data) {
        if (employeeMapper.exist(null, data.getNum())) {
            throw new RuntimeException("该员工已存在！");
        }
        employeeMapper.add(data);
        return data;
    }

    @Override
    public void delete(int id) {
        if (!employeeMapper.exist(id, null)) {
            throw new RuntimeException("id字段不存在！");
        }
        if(employeeMapper.getstate(id) == 999){
            throw new RuntimeException("员工已离职！");
        }
        employeeMapper.delete(id);
    }

    @Override
    public void update(Employee data) {
        if (!employeeMapper.exist(data.getId(), null)) {
            throw new RuntimeException("id字段不存在！");
        }
        //TODO 加个判断，如果状态修改为离职时离职时间比当前时间还晚改成当前时间
        employeeMapper.update(data);
    }

    @Override
    public List<SelectResult> select() {
        return employeeMapper.select();
    }

    @Override
    public Page<Employee> getList(EmployeeDTO data) {
        PageHelper.startPage(data.getPageNum(),data.getPageSize());
        return employeeMapper.getList(data);
    }

    @Override
    public Employee getCurrentUser() {
        if (!employeeMapper.exist(UserUtil.getUserId(), null)) {
            throw new RuntimeException("id字段不存在！");
        }
        return employeeMapper.getCurrentUser(UserUtil.getUserId());
    }

    @Override
    public Login login(Employee data) {
        Employee employee = employeeMapper.getEmployeeByNandP(data);
        if (employee != null && employee.getState() != 0){
            Login login = new Login();
            if(employeeMapper.isAdmin(data.getNum())){
                login.setIsAdmin(0);
            }else {
                login.setIsAdmin(1);
            }
            login.setToken(UserUtil.getToken(employee.getId()));
            return login;
        }
        else {
            throw new UserNameOrPasswordException();
        }
    }

    @Override
    public boolean hasPower(Integer employeeId, Integer permission) {
//        return employeeMapper.hasPower(employeeId,permission);
        return true;
    }

    @Override
    public List<EmployeePowerVO> getPowerListByEmployeeId() {
        List<Permission> permissionList = permissionMapper.getPermissionByEmployeeId(UserUtil.getUserId());

        //临时存在，用来找到父对象位置
        Map<Integer, EmployeePowerVO> temp = new HashMap<>();
        List<EmployeePowerVO> re = new ArrayList<>();
        for (Permission p : permissionList) {
            if (p.getData() == null) continue;

            ObjectMapper mapper = new ObjectMapper();
            mapper.setSerializationInclusion(JsonInclude.Include.ALWAYS);
            mapper.disable(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT);
            try {
                EmployeePowerVO EmployeePowerVO = mapper.readValue(p.getData(), EmployeePowerVO.class);
                if (p.getIsChildren() == 1) {
                    temp.put(p.getId(), EmployeePowerVO);
                    //有下级的话，给下级增加好对象
                    EmployeePowerVO.setChildren(new ArrayList<>());
                }

                //如果有上级，增加到上级，如果没有，直接增加到最顶级
                if (p.getParentId() != null) {
                    temp.get(p.getParentId()).getChildren().add(EmployeePowerVO);
                } else {
                    re.add(EmployeePowerVO);
                }
            } catch (JsonProcessingException e) {
                log.error("组织菜单出现异常。", e);
                throw new RuntimeException(e);
            }
        }
        return re;
    }

    @Override
    public void updatePwd(Employee data) {
        data.setId(UserUtil.getUserId());
        employeeMapper.updatePwd(data);
    }

    @Override
    public Integer isAdmin(String num) {
        if (employeeMapper.isAdmin(num)) {
            return 0;
        }
        return 1;
    }
}
